package com.mojo.concurrent.waitandnotify;

/**
 * 线程等待超时模式:适用于数据库连接池等类似获取资源的设计
 *
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
public class WaitAndNotify02 {

    public static void main(String[] args) {
        Thread thread = new Thread(new Timeout(5000L));
        thread.start();
    }

    static class Timeout implements Runnable {
        Long remaining;
        Long future = System.currentTimeMillis() + remaining;
        Object result = null;

        public Timeout(Long remaining) {
            this.remaining = remaining;
        }

        @Override
        public void run() {
            synchronized (this) {
                // 未超时且未得到期望结果
                while (result == null && remaining > 0) {
                    try {
                        wait(remaining);
                        // 重置超时持续时间
                        remaining = future - System.currentTimeMillis();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            result = "默认结果";
            System.out.println("结果：" + result);
        }
    }
}
